var express = require('express');
var router = express.Router();
// var MongoClient=require('mongodb').MongoClient;
// var dbpath='mongodb://localhost:27017'
// var dbname='lcyblog'
var dbconnect=require('../models/dbconnect.js')
// var crypto=require('crypto')
// var md5=crypto.createHash('md5')
var md5 = require('md5')
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
//http://127.0.0.1:3000/users/register
//路由基于 users


//注册页面
router.get('/register', function(req, res, next) {
  res.render('register',{
    username:req.session.username
  })
});
//注册接口
router.post('/reg',function(req,res){
  console.log(req.body)
  
dbconnect('user').then(function({coll,dbCon}){
   //先查询判断数据库是否已经存在用户名否则的不能插入
   //保存的密码进行加密
   let time = new Date()
   let timeStr = `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}  ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`
   var pw=md5(req.body.password)
   console.log(pw)
   var obj={
    username:req.body.username,
    password:pw,
    regDate:timeStr,
  }
  coll.find({username:req.body.username}).toArray(function(error,data){
      if(error) throw error;
      console.log(data.length)
      if(data.length>0){
        res.json({
          code:0,
          msg:'用户名已被注册'
        })
        dbCon.close();
      }else{
        //插入数据
        coll.insertOne(obj,function(error,data){
          console.log(data)
          res.json({
            code:1,
            msg:'注册成功'
          })
          dbCon.close();
        })
      }
    })
  
})



})




//登录页
router.get('/login',function(req,res,next){
  res.render('login',{
    username:req.session.username
  })
 
})

//登录接口
router.post('/log',function(req,res){

    var pw=md5(req.body.password)
    var userObj={
      username:req.body.username,
      password:pw,
    }
   
dbconnect('user').then(function({coll,dbCon}){

  coll.find(userObj).toArray(function(error,data){
          if(error) throw error;
          console.log(data.length)
          if(data.length==0){
            res.json({
              code:0,
              msg:'登录失败'
            })
            dbCon.close()
          }else{
            //登录时保存用户名 存了session
            req.session.username=data[0].username
            console.log(req.session)
            res.json({
              code:1,
              msg:'登录成功'
            })
          
            dbCon.close()
          }
         
        })


}).catch(function(error){
  console.log(error)
})


})
//注销接口
router.get('/relogin',function(req,res){
  req.session.destroy((error)=>{
    if(error){
      console.log(error)
    }else{
      res.redirect('/')
    }
  })
})

//发布文章
router.post('/publish',function(req,res){
  let time = new Date()
  let timeStr = `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}  ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`
    var pubArticle={
      arctitle: req.body.arctitle,
      content: req.body.content,
      pubtime:timeStr,
    }
    //插入数据库
    dbconnect('article').then(function({coll,dbCon}){
      coll.insertOne(pubArticle,function(error,data){
        if(error) throw error;
        res.json({
          code:1,
          msg:'发布成功',
        })
      })
    }).catch(function(error){
      console.log(error)
    })
})
//文章详情
//把id转为object对象 查询时候用
var ObjectId=require('mongodb').ObjectId
//根据 id查询文章
router.get('/articles/post/:id',(req,res)=>{
  console.log(req.params.id)
  console.log(new ObjectId(req.params.id))
  var arcId=new ObjectId(req.params.id)
  dbconnect('article').then(function({coll,dbCon}){
    coll.find({'_id':arcId}).toArray(function(error,data){
      if(error) throw error;
      console.log(data[0].arctitle)
       res.render('article',{
             article:data,
             username:req.session.username,
          })
    })
  }
  )
})









module.exports = router;
